package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.mapper.PeachBlossomMapper;
import com.tanhua.server.mapper.PeachBlossomScheduledMapper;
import com.tanhua.server.mapper.UserInfoMapper;
import com.tanhua.server.pojo.PeachBlossom;
import com.tanhua.server.pojo.PeachBlossomScheduled;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PeachBlossomVo;
import com.tanhua.server.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName PeachBlossomService
 * @Description TODO
 * @Author JavaDev
 * @Date 2021/1/18 8:56
 * @Version 1.0
 */
@Service
@EnableScheduling
@Slf4j
public class PeachBlossomService {

    private final Integer remainingTimes = 8;// 设置默认每天可以使用桃花传音的次数


    @Autowired
    private PeachBlossomScheduledMapper peachBlossomScheduledMapper;

    @Autowired
    private PeachBlossomMapper peachBlossomMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    public void savePeachBlossom(MultipartFile soundFile) throws Exception {

        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                StringUtils.substringAfter(soundFile.getOriginalFilename(), "."), null);

        PeachBlossom peachBlossom = PeachBlossom.builder()
                .userId(UserThreadLocal.get().getId())
                .soundUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath())
                .build();

        peachBlossomMapper.insert(peachBlossom);
    }


    /**
     * 桃花传音-接收语音（学生实战）
     *
     * @return
     */
    public PeachBlossomVo queryPeachBlossom() {
        Long userId = UserThreadLocal.get().getId();

        List<PeachBlossom> peachBlossoms = peachBlossomMapper.selectList(new LambdaQueryWrapper<PeachBlossom>().ne(PeachBlossom::getUserId, userId));
        if (CollectionUtils.isEmpty(peachBlossoms)) {
            return null;
        }

        // 用了一次桃花传音的机会就更新一次减一
        String remainingTimesStr = redisTemplate.opsForValue().get("PEACH_BLOSSOM_RESET_TIMES" + userId);
        if (remainingTimesStr == null || Integer.valueOf(remainingTimesStr).equals(0)) {
            return null;
        }

        Integer remainingTimes = Integer.valueOf(remainingTimesStr) - 1;
        redisTemplate.opsForValue().set("PEACH_BLOSSOM_RESET_TIMES" + userId, remainingTimes + "");

        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserId, userId));


        PeachBlossom peachBlossom = peachBlossoms.get(RandomUtils.nextInt(0, peachBlossoms.size()));
        PeachBlossomVo peachBlossomVo = PeachBlossomVo.builder()
                .id(Math.toIntExact(peachBlossom.getUserId()))
                .avatar(userInfo.getLogo())
                .nickname(userInfo.getNickName())
                .age(userInfo.getAge())
                .gender(userInfo.getSex().equals(SexEnum.MAN.getValue()) ? SexEnum.MAN.toString() : SexEnum.WOMAN.toString())
                .soundUrl(peachBlossom.getSoundUrl())
                .remainingTimes(remainingTimes)
                .build();
        return peachBlossomVo;
    }


    //每天凌晨1点执行一次："0 0 1 * * ?"
    //@Scheduled(cron = "0 0 1 * * ?")
    @Scheduled(fixedRate = 5 * 60 * 1000)
    private void configureTasks() {
        log.info("桃花传音每日定期复位用户使用桃花传音的次数");
        log.info("执行静态定时任务时间(每五分钟执行一次): " + LocalDateTime.now());


        List<UserInfo> userInfoList = userInfoMapper.selectList(null);
        Set<Long> userInfoIds = userInfoList.stream().map(UserInfo::getUserId).collect(Collectors.toSet());

        for (Long userInfoId : userInfoIds) {
            // 复位为每天指定次数
            redisTemplate.opsForValue().set("PEACH_BLOSSOM_RESET_TIMES" + userInfoId, remainingTimes + "", 1, TimeUnit.DAYS);

        }
    }
}